package com.longxi.tianjintianbao.ui.presenter.department;

import android.app.Activity;
import android.content.Intent;

import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.HttpResult;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.listener.SelectDepartmentListener;
import com.longxi.tianjintianbao.listener.SelectPersonnelListener;
import com.longxi.tianjintianbao.model.Personnel;
import com.longxi.tianjintianbao.ui.activity.PersonnelActivity;
import com.longxi.tianjintianbao.ui.adapter.multitype.DepartmentViewBinder;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.presenter.repair.PersonnelAtPresenter;
import com.longxi.tianjintianbao.ui.view.department.IDepartmentAtView;
import com.longxi.tianjintianbao.utils.MyUtils;
import com.longxi.tianjintianbao.utils.NListRefresh;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class DepartmentAtPresenter extends BasePresenter<IDepartmentAtView> {

    private MultiTypeAdapter adapter;
    private Items items;
    List<String> ids = new ArrayList<>();
    List<Personnel> personnels = new ArrayList<>();
    boolean mIsMulti = false;

    public DepartmentAtPresenter(BaseActivity context) {
        super(context);
    }

    public void setBar() {
        mContext.setTitle("部门列表");
        mContext.setTvLeft("返回");
        mContext.setTvRight("确定");
        mIsMulti = mContext.getIntent().getBooleanExtra(AppConst.MULTI_SELECTION, false);
        personnels = (List<Personnel>) mContext.getIntent().getSerializableExtra(AppConst.PERSONNEL_LISTINTENT);
    }

    public void initAdapter(){
        if(adapter == null){
            adapter = new MultiTypeAdapter();
            SelectPersonnelListener selectAreaListener = new SelectPersonnelListener() {

                @Override
                public void onSelectPersonnel(Personnel personnel, int position) {
                    multiSelection(personnel, position);
                }
            };
            SelectDepartmentListener selectDepartmentListener = new SelectDepartmentListener() {

                @Override
                public void onSuccess(Personnel personnel, int position) {
                    multiSelection(personnel, position);
                    toPersonnelActivity();
                }
            };
            adapter.register(Personnel.class, new DepartmentViewBinder(selectAreaListener, selectDepartmentListener));
            getView().getRvContent().setAdapter(adapter);
        }
    }

    public void getDepartment(){

        JSONObject object = new JSONObject();
        try {
            object.put("userid", MyApplication.loginUser.userid);
            object.put("deptid", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().getPersonnel(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<HttpResult<Personnel>>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideLoading();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(HttpResult<Personnel> result) {
                if(personnels != null && personnels.size() > 0){
                    for (int i = 0; i < result.getData().size(); i++) {
                        for (int j = 0; j < personnels.size(); j++) {
                            if(personnels.get(j).getDeptid().equals(result.getData().get(i).getDeptid()) && !result.getData().get(i).isSelect()){
                                result.getData().get(i).setSelect(true);
                                ids.add(result.getData().get(i).getDeptid());
                            }
                        }
                    }
                }

                items = NListRefresh.getInstance().fjData(result,
                        getView().getRefreshLayout(),
                        items,
                        adapter,
                        mContext);

            }
        });
    }

    /**
     * 多选
     */
    public void multiSelection(Personnel personnel, int position){
        if(personnel.isSelect()){
            ids.remove(personnel.getDeptid());
            personnel.setSelect(false);
        }else{
            ids.add(personnel.getDeptid());
            personnel.setSelect(true);
        }
        adapter.notifyItemChanged(position);
    }

    public void toPersonnelActivity() {
        if(ids.size() == 0){
            MyUtils.showToast("请选择部门");
            return;
        }
        Intent mainIntent = new Intent(mContext, PersonnelActivity.class);
        mainIntent.putExtra(AppConst.DEPTID,ids.toString().substring(1, ids.toString().length() - 1));
        mainIntent.putExtra(AppConst.MULTI_SELECTION,mIsMulti);
        mainIntent.putExtra(AppConst.PERSONNEL_LISTINTENT, (Serializable) personnels);
        mContext.startActivityForResult(mainIntent, AppConst.IntentRequstCode.ACTIVITY_DEPARTMENT_TO_PERSONNEL);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == AppConst.IntentRequstCode.ACTIVITY_DEPARTMENT_TO_PERSONNEL) {
            if(data != null){
                List<Personnel> personnels = (List<Personnel>) data.getSerializableExtra(AppConst.PERSONNEL_LISTINTENT);
                Intent intent = new Intent();
                intent.putExtra(AppConst.PERSONNEL_LISTINTENT,  (Serializable) personnels);
                mContext.setResult(Activity.RESULT_OK, intent);
                mContext.finish();
            }
        }
    }

}
